import shutil
import sys
from pathlib import Path

from third_lib_tool import logs
from third_lib_tool.util.cmake_util import cmake_build_and_install
from third_lib_tool.util.compress_util import smart_unpack
from third_lib_tool.util.version_util import find_newest_lib


def unpack(archive_file_dir: Path, extract_dir: Path) -> Path:
    return smart_unpack(
        archive_file=find_newest_lib(archive_file_dir, 'libssh2-?.?.?.tar.gz'),
        unpack_dir=extract_dir,
        base_name='libssh2.src'
    )


def install(source_dir: Path, build_dir: Path, install_dir: Path, openssl_install_dir: Path):
    other_params: str = ''
    if sys.platform == 'win32':
        other_params = '-DCMAKE_C_FLAGS_RELEASE=/MT'
    cmake_build_and_install(
        source_dir=source_dir,
        build_dir=build_dir,
        install_dir=install_dir,
        build_config='Release',
        cmake_prefix_path=[str(openssl_install_dir)],
        build_shared_libs=True,
        other_params=other_params
    )


def prepare(thirdlibs_repo_dir: Path, base_dir: Path, openssl_install_dir: Path):
    if base_dir.exists():
        logs.log_skip('libssh2', base_dir)
        return
    source_dir = unpack(
        archive_file_dir=thirdlibs_repo_dir / 'libssh2',
        extract_dir=base_dir
    )
    install_dir: Path = base_dir / 'install'
    install(
        source_dir=source_dir,
        build_dir=source_dir / 'build-release',
        install_dir=install_dir,
        openssl_install_dir=openssl_install_dir
    )
    # 在 Windows 平台中，CMake 查找 ssh2 库时不会尝试添加 lib 前缀，所以复制不带前缀的库文件
    if sys.platform == 'win32':
        dll_file: Path = install_dir / 'bin' / 'libssh2.dll'
        if dll_file.exists():
            shutil.copy(src=dll_file, dst=dll_file.parent / 'ssh2.dll')
        lib_file: Path = install_dir / 'lib' / 'libssh2.lib'
        if lib_file.exists():
            shutil.copy(src=lib_file, dst=lib_file.parent / 'ssh2.lib')

